import { useState, useCallback } from 'react';
import { isEmpty as _isEmpty, isEqual as _isEqual } from 'lodash';
import type { SearchFormSchema } from './index';
import moment from 'moment';
import type { OperatorType } from './operators';
import type { SystemFilter as Filter, SystemFilterItem as FilterItem, View } from './interface';

const DATE_FORMAT = 'YYYY-MM-DD';

/**
 * 获取获取与更新本地数据的勾子
 * @param searchKey 唯一的key
 * @param initValue 初始默认值
 */
export function useLocalStorage<T>(searchKey: string, initValue: T): [T, (params: T) => void] {
  const [localData, setLocalData] = useState<T>(() => {
    const localDataString = localStorage.getItem(searchKey);
    const localFields = localDataString ? JSON.parse(localDataString) : initValue;
    return localFields;
  });

  const setLocalStorage = useCallback((list: T) => {
    setLocalData(list);
    localStorage.setItem(searchKey, JSON.stringify(list));
  }, []);

  return [localData, setLocalStorage];
}

// 获取schema中的默认值
export async function getDefaultParams(schema: SearchFormSchema, immediate = false) {
  const tempDefaultParams: any = {};

  // 使用 for 循环代替 reduce，以支持异步处理
  for (const [key, item] of Object.entries(schema)) {
    let options: any;
    if (immediate) {
      options = {
        initialValue: item,
      };
    } else {
      options = item?.options || {};
    }
    if (options.initialValue !== undefined) {
      // 处理 initialValue 可能是函数（包括异步函数）的情况
      if (typeof options.initialValue === 'function') {
        try {
          // 等待函数执行结果
          const value = await options.initialValue();
          tempDefaultParams[key] = value;
        } catch (error) {
          console.error(`Error getting initialValue for ${key}:`, error);
        }
      } else {
        // 直接值赋值
        tempDefaultParams[key] = options.initialValue;
      }
    }
  }
  return tempDefaultParams;
}

// 处理Date类型数据
export const getDateValue = (value: any, format: string, needFormat = true) => {
  let value_;
  if (value instanceof moment) {
    value_ = needFormat ? value.format(format) : value;
  } else if (typeof value === 'string') {
    value_ = needFormat ? moment(value, format).format(format) : moment(value, format);
  }
  return value_;
};

/**
 * 格式化初始参数
 * 目前主要处理为日期的字段
 */
export function formatInitParams(initParams: any, schema: SearchFormSchema) {
  const res = { ...initParams };
  // 找到schema中的日期字段列表
  Object.entries(schema).forEach(([key, item]: [string, any]) => {
    const { componentType, props = {} } = item;
    let currentValue = res[key];
    // 处理日期
    if (['DatePicker'].includes(componentType)) {
      let format = DATE_FORMAT;
      if (props.format) {
        format = props.format;
      }
      currentValue = getDateValue(currentValue, format, false);
    }
    // 处理如期区间
    if (componentType === 'RangePicker' && !_.isEmpty(currentValue)) {
      const [start, end] = currentValue as [any, any];
      let format = DATE_FORMAT;
      if (props.format) {
        format = props.format;
      }
      currentValue = [getDateValue(start, format, false), getDateValue(end, format, false)];
    }
    res[key] = currentValue;
  });
  return res;
}

interface ResolveValueProps {
  params: any; // 查询条件
  schema: SearchFormSchema;
  handleNull?: boolean; // 特性处理IS_NOT_NULL与IS_NULL
  type: 'search' | 'filter'; // 操作类型
  isNormalSearch: boolean; // 是否是普通查询(非SmartSearch查询)
  isCompatibilityMode?: boolean; // 是否是兼容模式
}

/**
 * 解析查询参数
 * @param props
 */
export const resolveValue = (props: ResolveValueProps) => {
  const { params, schema, type: resolveType, isNormalSearch, isCompatibilityMode } = props;
  // 处理值
  let res: FilterItem[] = Object.entries(params).map(([key, value]) => {
    let fieldName = '';
    let operator: OperatorType = 'EMPTY';
    let value_ = value;
    if (key.includes(':')) {
      const arr = key.split(':');
      fieldName = arr[0];
      operator = arr[1] as OperatorType;
    } else {
      fieldName = key;
    }
    // 当前字段
    const currentFiled = schema[key] || {};
    const { CUSTOM_TYPE: type, componentType = 'Input', props = {} } = currentFiled;

    // 处理SmartSearch相关
    if (!isNormalSearch) {
      // 处理IS_NOT_NULL与IS_NULL
      if (['IS_NOT_NULL', 'IS_NULL'].includes(operator)) {
        value_ = value !== false ? null : false;
      }

      // 仅在查询时处理
      if (resolveType === 'search') {
        // 处理IN与NOT_IN
        if (['IN', 'NOT_IN'].includes(operator) && value) {
          if (['string', 'number'].includes(type) && typeof value === 'string') {
            value_ = value.split(/,|，/);
          }
          if (type === 'number' && typeof value === 'number') {
            value_ = [value];
          }
        }
        // 处理金额
        if (componentType === 'InputMoney' && value && typeof value === 'string') {
          value_ = value.replace(/,|，/g, '');
        }
      }
    }

    return {
      fieldName,
      operator,
      value: value_,
    };
  });

  // 过滤掉无效值
  res = res.filter(({ value, operator }) => {
    // 空字符串
    if (typeof value === 'string' && value.trim() === '') {
      return false;
    }
    // 处理IN与NOT_IN
    if (['IN', 'NOT_IN'].includes(operator) && ((Array.isArray(value) && value.length === 0) || !value)) {
      return false;
    }
    // 仅在查询时过滤
    if (resolveType === 'search') {
      if (['IS_NOT_NULL', 'IS_NULL'].includes(operator) && value === false) {
        return false;
      }
    }
    return value !== undefined;
  });

  // 普通查询模式与高级查询(兼容)模式下查询
  if ((isCompatibilityMode && resolveType === 'search') || isNormalSearch) {
    res = res.reduce((tempRes: any, { value, fieldName }: any) => {
      tempRes[fieldName] = value;
      return tempRes;
    }, {});
  }

  return res;
};

/**
 * 根据filterItems获取对应值
 * @param data
 */
export function getValues(data: any[] | any, schema: SearchFormSchema, isCompatibilityMode: boolean | undefined) {
  let values = {};
  if (_isEmpty(data)) return values;
  // 高级查询
  if (Array.isArray(data)) {
    data.map((item) => {
      const { fieldName, operator, value } = item;
      const propsName = operator && !isCompatibilityMode ? `${fieldName}:${operator}` : fieldName;
      values[propsName] = value;
    });
  } else {
    // 普通查询
    values = { ...(data as any) };
  }

  return values;
}

/**
 * 移除对象中值为undefine的属性
 * @param obj
 */
function deleteObjectUndefinedValue(obj: object) {
  const copyObj = { ...obj };
  Object.entries(copyObj).forEach(([key, value]) => {
    if (value === undefined) {
      delete copyObj[key];
    }
  });
  return copyObj;
}

/**
 * 比较两个对象的属性不为undefine的部分是否相等
 * @param obj1
 * @param obj2
 */
export function isEqualImpl(obj1: object, obj2: object) {
  const copyObj1 = deleteObjectUndefinedValue(obj1);
  const copyObj2 = deleteObjectUndefinedValue(obj2);
  return _isEqual(copyObj1, copyObj2);
}

/**
 * 将数组的排序字段转换为对象排序字段
 * @param orderList
 * @param isCompatibilityMode
 */
export function getOrderInfo(orderList: any[], isCompatibilityMode = false): any[] | Object {
  let res = orderList;
  if (isCompatibilityMode) {
    res = orderList.reduce((tempRes: any, item: any) => {
      const { fieldName, orderType } = item;
      tempRes[fieldName] = orderType;
      return tempRes;
    }, {});
  }
  return res;
}
